#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   DeviceManage.py
@Time    :   2020/07/21 16:18:38
@Author  :   Xiong qiufeng
@Version :   1.0
@Contact :   1528399071@qq.com
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Desc    :   None
'''

import os
import copy
import json
from collections import OrderedDict

import PyQt5_stylesheets
import qtawesome as qta

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from common.libs.Log import logger

from .DeviceService import DeviceServiceJson

from ui.deviceSmart import Ui_Form
from ui.deviceSmartAddAction import Ui_Dialog as AddActionDialog
from ui.deviceSmartAddCondition import Ui_Dialog as AddConditionDialog

class AddConditionDlg(QDialog, AddConditionDialog):
    devices = []
    def __init__(self, parent = None):
        super(QDialog, self).__init__(parent)
        self.setupUi(self)
        self.pushButton_add.clicked.connect(self.accept)

    def accept(self):
        QDialog.accept(self)

class AddActionDlg(QDialog, AddActionDialog):
    devices = []
    def __init__(self, parent = None):
        super(QDialog, self).__init__(parent)
        self.setupUi(self)
        self.pushButton_add.clicked.connect(self.accept)

    def accept(self):
        QDialog.accept(self)

CONFIG_DEVICE_SMART = os.getcwd()+'/conf/device_smart.json'
class DeviceSmartWidget(QWidget, Ui_Form):

    devices = []
    scenes = []

    listView_select_row = 0

    def __init__(self, parent = None):
        super(QWidget, self).__init__(parent)
        self.setupUi(self)
        self.device_service = DeviceServiceJson()
        self.devices = self.device_service.getAll()

        self.addConditionDlg = AddConditionDlg()
        self.addActionDlg = AddActionDlg()
        # 表格初始化
        self.tableWidgetConditionInit()
        self.tableWidgetActionInit()
        # 信号初始化
        # self.signalInit()
        self.listViewInit()
        self.listViewLoad()

        self.pushButton_add_action.clicked.connect(self.addAction)
        self.pushButton_add_condition.clicked.connect(self.addCondition)

    def listViewInit(self):
        self.scene_model = QStringListModel()
        self.listView.setModel(self.scene_model)
        self.listView.clicked.connect(self.listViewItemClicked)

    def tableWidgetConditionInit(self):
        # self.tableWidget_condition.clicked.connect(self.tableWidgetConditionItemClicked)
        self.tableWidget_condition.setColumnCount(2)	
        self.tableWidget_condition.setHorizontalHeaderLabels(['设备', '状态'])
        # 下面代码让表格100填满窗口
        self.tableWidget_condition.horizontalHeader().setStretchLastSection(True)
        self.tableWidget_condition.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # 多选
        self.tableWidget_condition.setSelectionBehavior(QAbstractItemView.SelectRows)
        # self.setSelectionMode(QAbstractItemView.ExtendedSelection)

    def tableWidgetActionInit(self):
        # self.tableWidget_action.clicked.connect(self.tableWidgetActionItemClicked)
        self.tableWidget_action.setColumnCount(2)	
        self.tableWidget_action.setHorizontalHeaderLabels(['设备', '动作'])
        # 下面代码让表格100填满窗口
        self.tableWidget_action.horizontalHeader().setStretchLastSection(True)
        self.tableWidget_action.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # 多选
        self.tableWidget_action.setSelectionBehavior(QAbstractItemView.SelectRows)
        # self.setSelectionMode(QAbstractItemView.ExtendedSelection)

    def read(self):
        try:
            with open(CONFIG_DEVICE_SMART, 'r', encoding='utf-8') as f:
                self.scenes = json.loads(f.read(), object_pairs_hook=OrderedDict)
                print(self.scenes)
                # self.devices = sorted(devices, key=lambda k: k['id'])
                # self.devices = copy.deepcopy(devices)
                return scenes 
        except Exception as e:
            logger.info(e)
            return False

    def write(self):
        try:
            save = json.dumps(self.scenes, indent=4)
            with open(CONFIG_DEVICE_SMART, 'w', encoding='utf-8') as f:
                f.write(save)
        except Exception as e:
            logger.info(e)
            return False

    def show(self):
        self.listViewLoad()
        QWidget.show(self)

    def addAction(self):
        self.addActionDlg.exec()

    def addCondition(self):
        self.addConditionDlg.exec()

    def tableWidgetConditionLoad(self, items):
        self.tableWidget_condition.clear()
        self.tableWidget_condition.setRowCount(len(items))
        self.tableWidget_condition.setHorizontalHeaderLabels(['设备', '状态'])

        for i, element in enumerate(items):
            for device in self.devices:
                if device['value']['sn'] == element['sn']:
                    self.tableWidget_condition.setItem(i, 0, QTableWidgetItem(str('%s(%s)'%(device['value']['name'], device['value']['position']))))
                    self.tableWidget_condition.setItem(i, 1, QTableWidgetItem(str(element['name'])))
                    break

    def tableWidgetActionLoad(self, items):
        self.tableWidget_action.clear()
        self.tableWidget_action.setRowCount(len(items))
        self.tableWidget_action.setHorizontalHeaderLabels(['设备', '动作'])

        for i, element in enumerate(items):
            for device in self.devices:
                if device['value']['sn'] == element['sn']:
                    self.tableWidget_action.setItem(i, 0, QTableWidgetItem(str('%s(%s)'%(device['value']['name'], device['value']['position']))))
                    self.tableWidget_action.setItem(i, 1, QTableWidgetItem(str(element['name'])))
                    break

    def listViewItemClicked(self, item):
        self.listView_select_row = item.row()
        condition = self.scenes[item.row()]['condition']
        action = self.scenes[item.row()]['action']
        print(condition)
        print(action)
        self.tableWidgetConditionLoad(condition)
        self.tableWidgetActionLoad(action)

    def listViewLoad(self):
        self.read()
        # self.scene_model.clear()
        self.scene_model.setStringList([n['name'] for n in self.scenes])

    
